<template>
  <a-card>
    <!-- 查询区域 -->
    <a-form layout="horizontal" :labelCol="{ span: 8 }" :wrapperCol="{ span: 15 }">
      <a-row>
        <a-col :md="6" :sm="24">
          <a-form-item label="部门名称">
            <a-input
              allowClear
              v-model="searchForm.deptName"
              placeholder="部门名称"
              @keyup.enter="handleSearch"
            />
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item label="是否监管部门">
            <a-radio-group style="width: 100%;" v-model="searchForm.deptType">
              <a-radio :value="null">全部</a-radio>
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button class="ml-8" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 表格区域 -->
    <div>
      <div class="operator">
        <a-button class="mr-8" type="primary" @click="handleAdd">新增</a-button>
        <!-- <a-button
          type="danger"
          :class="{ 'btn-disabled': !rowSelection.selectedRowKeys.length }"
          @click="handleDelAll"
          >批量删除</a-button
        > -->
      </div>
      <a-table
        :columns="columns"
        :row-key="item => item.id"
        :data-source="dataSource"
        :loading="loading"
        :row-selection="rowSelection"
        bordered
      >
        <span slot="tags" slot-scope="deptType">
          <a-tag color="green">{{ deptType === 1 ? '是' : '否' }}</a-tag>
        </span>
        <span slot="action" slot-scope="item">
          <a @click="handleEdit(item)">修改</a>
          <a-divider type="vertical" />
          <a style="color: #ff4d4f" @click="handleDel(item)">删除</a>
        </span>
      </a-table>
    </div>

    <!-- 新增/修改弹窗 -->
    <a-modal
      title="新增部门"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="部门名称"
        >
          <a-input
            v-decorator="['deptName', { rules: [{ required: true, message: '请输入部门名称' }] }]"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="部门说明"
        >
          <a-textarea
            v-decorator="['deptDesc', { rules: [] }]"
            placeholder="请输入部门说明"
            :rows="4"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="是否监管部门"
        >
          <a-radio-group
            v-decorator="[
              'deptType',
              {
                rules: [{ required: true, message: '请选择是否监管部门' }],
                initialValue: 0,
              },
            ]"
          >
            <a-radio :value="0">否</a-radio>
            <a-radio :value="1">是</a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="排序号'">
          <a-input v-decorator="['deptOrder', { rules: [{ required: true, message: '请输入排序号' }] }]" placeholder="请输入排序号" />
        </a-form-item> -->
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { basicService } from '@/services';

const columns = [
  {
    title: '部门id',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
  },
  {
    title: '部门名称',
    dataIndex: 'deptName',
    key: 'deptName',
    align: 'center',
  },
  {
    title: '部门说明',
    key: 'deptDesc',
    dataIndex: 'deptDesc',
    align: 'center',
  },
  {
    title: '是否监管部门',
    key: 'deptType',
    dataIndex: 'deptType',
    scopedSlots: { customRender: 'tags' },
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
];

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'basicDept',

  data() {
    return {
      formItemLayout,
      columns: columns,
      // 搜索表单
      searchForm: {
        deptName: '',
        deptType: null,
      },
      dataSource: [],
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      form: this.$form.createForm(this, { name: 'dept-form' }),
      confirmLoading: false,
      selectedItem: null,
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
    };
  },

  created() {
    this.getDataSource();
  },

  methods: {
    // 查询
    handleSearch() {
      this.getDataSource();
    },

    // 重置
    handleReset() {
      this.searchForm = {
        deptName: '',
        deptType: null,
      };
    },

    // 新增
    handleAdd() {
      this.type = 1;
      this.visible = true;
    },

    // 删除部门
    handleDel(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该部门吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            basicService
              .delDept({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getDataSource();
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改部门
    handleEdit(item) {
      console.log(item);
      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          deptName: item.deptName,
          deptDesc: item.deptDesc,
          deptType: item.deptType,
        });
      });
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.form.resetFields();
    },

    // 新建/修改部门确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            basicService
              .addDept(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            basicService
              .updateDept({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource();
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
                this.selectedItem = null;
              });
          }
        }
      });
    },

    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
      const that = this;
      const idList = this.rowSelection.selectedRowKeys;

      this.$confirm({
        title: '确认删除吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return new Promise(resolve => {
            basicService
              .delDeptList({ idList })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getDataSource();
                }
              })
              .finally(() => resolve())
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 获取数据
    getDataSource() {
      this.loading = true;

      const params = {
        needDetail: true,
        canChoose: false,
        ...this.searchForm,
      };

      basicService.getDeptList(params).then(res => {
        if (res.code === '200') {
          console.log(res);
          this.dataSource = res.data.items;
          this.loading = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
